﻿using Consul;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Hosting;
using Newtonsoft.Json;
using SCZS.Example.Core.ConsulExtend.ServerExtend;
using SCZS.Example.Core.ConsulExtend;
using System;
using Microsoft.Extensions.Configuration;

namespace SCZS.Example.Core.Middlewares
{
    public static class ConsulMiddleware
    {
        public enum UseConsulType
        {
            HTTP,
            GRPC
        }

        /// <summary>
        /// 自动读取配置文件完成注册
        /// </summary>
        /// <param name="app"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static async Task UseConsulMiddle(this IApplicationBuilder app, IConfiguration configuration, IHostApplicationLifetime lifetime, UseConsulType type = UseConsulType.HTTP)
        {
            ConsulRegisterOption consulRegisterOption = new ConsulRegisterOption();
            configuration.Bind("ConsulRegisterOption", consulRegisterOption);

            ConsulClientOption consulClientOption = new ConsulClientOption();
            configuration.Bind("ConsulClientOption", consulClientOption);
            switch (type)
            {
                case UseConsulType.HTTP:
                    await ConsulRegiterExtend.UseConsul(app, consulClientOption, consulRegisterOption, lifetime);
                    break;
                case UseConsulType.GRPC:
                    await gRPCConsulRegiterExtend.UseGRPCConsul(app, consulClientOption, consulRegisterOption, lifetime);
                    break;
                default:
                    break;
            }
        }

    }
}
